# -*- coding: utf-8 -*-
# owner: shenyi
# src/utils/env.py
import re
from pathlib import Path
from typing import Dict

def read_env_file(path: Path) -> Dict[str, str]:
    """从 .env 文件读取键值对（忽略注释和空行）"""
    env_vars = {}
    if not path.exists():
        return env_vars

    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                match = re.match(r'^\s*([^=]+)\s*=\s*"?(.*?)"?\s*$', line)
                if match:
                    key, val = match.groups()
                    env_vars[key] = val
    return env_vars


def write_env_file(path: Path, env_vars: Dict[str, str]) -> None:
    """将键值对写入 .env 文件，并设置安全权限"""
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write("# CloudKit 自动配置文件\n")
        for key in sorted(env_vars):
            val = env_vars[key]
            f.write(f'{key}="{val}"\n')
    path.chmod(0o600)